from tkinter import *
import random
from ConvertImage import readImage,Image2Array,Array2Photo,Arrays2Photos
from SplitImage import splitArray,initProper
from Control import get_mouse_xy,flash_piece,release_piece,pick_piece
import Control
import sys

nx=3
ny=3
puzzle_name='pt/1.jpeg'
seat_name='pt/seat.jpeg'
bg_name='pt/bg.jpg'
init_id=0

args=list(sys.argv[1:])
len_args=len(args)
if len_args>=3:
    nx,ny=(int(args[0]),int(args[1]))
    puzzle_name=args[2]
    if len_args>=4:
        seat_name=args[3]
        if len_args>=5:
            bg_name=args[4]

print(nx,ny)
print(bg_name,seat_name)
root = Tk()
root.title("拼图游戏")

image = readImage(puzzle_name)
image_array = Image2Array(image)

image_width=image_array.shape[1]
image_height=image_array.shape[0]

canvas = Canvas(root,width=image_width, height=image_height)
canvas.pack()

#初始化P
proper=initProper(nx,ny,0)
image_arrays,proper,piece_width,piece_height = splitArray(image_array,image_width,image_height,proper,nx,ny)
photos = Arrays2Photos(image_arrays)

#绘制背景
if bg_name:
    bg_photo = Array2Photo(Image2Array(readImage(bg_name)))
    init_id=canvas.create_image(int(image_width/2),int(image_height/2),image=bg_photo,tags=("piece",))

#绘制座位
if seat_name:
    seat_photo = Array2Photo(Image2Array(readImage(seat_name).resize((int(piece_width/3),int(piece_width/3)))))
    for i in range(len(photos)):
        init_id=canvas.create_image(proper[i,6]+piece_width/2,proper[i,7]+piece_height/2,image=seat_photo,tags=("piece",))

#绘制初始
for i,piece in enumerate(photos):
    init_id=canvas.create_image((proper[i,0]+proper[i,1])/2,(proper[i,2]+proper[i,3])/2,image=piece,tags=("piece",))
    proper[i,4]=init_id

print(proper)

Control.proper=proper
Control.canvas=canvas
Control.photos=photos


#绑定鼠标事件
canvas.bind("<B1-Motion>",flash_piece)  #拖动左键，移动图片
canvas.bind("<Button-1>",pick_piece)  #点击左键，确定图片编号
canvas.bind("<ButtonRelease-1>",release_piece)  #右键删除
root.bind("<Motion>",get_mouse_xy)  #移动鼠标获取坐标
root.mainloop()